package com.baiytfp.hf.HFDataExchange.common.utils;

import com.baiytfp.hf.HFDataExchange.common.model.state.RecordType;
import com.baiytfp.hf.HFDataExchange.common.model.state.RightBelongType;
import com.baiytfp.hf.baiytfp.framework.model.state.Status;
import com.baiytfp.hf.baiytfp.hfutils.HFConfig;
import com.baiytfp.hf.baiytfp.framework.model.state.YesOrNo;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateModelException;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FtlUtil {
	// 需要注入给freemarker使用的class
	private static Class[] defaultStaticClasses = {

		YesOrNo.class,
		Status.class,
		RightBelongType.class,
		RecordType.class,
	};

	/**
	 * 将class的引用注入给freemarker，作用域为request
	 * @param modelMap
	 */
	public static void setDefaultStaticModel(ModelAndView modelMap) {
		for (Class clz : defaultStaticClasses) {
			String name = clz.getSimpleName();
			modelMap.addObject(name, getStaticModel(clz));
		}
	}
	public static void setDefaultStaticModel(ModelMap modelMap) {
		for (Class clz : defaultStaticClasses) {
			String name = clz.getSimpleName();
			modelMap.addAttribute(name, getStaticModel(clz));
		}
	}
	
	/**
	 * 获取freemarker可使用的bean
	 * @param clz 类型
	 * @return
	 */
	private static Object getStaticModel(Class clz) {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        try {
            return wrapper.getStaticModels().get(clz.getName());
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
        return null;
    }

	// 取得本系统默认Root
	public static Map getFtlRoot(HttpServletRequest request) throws Exception {
		Map root = new HashMap();
		root.put("path", PathInfo.getAppPath(request));
		root.put("siteName", HFConfig.getIstance().getDBConfig("siteName", ""));

		root.put("currentTime", (new Date()).getTime() + "");

//		FtlUtil.setDefaultStaticModel(root);

		return root;
	}
}
